package cn.tedu.dfxd.controller;


import cn.tedu.dfxd.entity.User;
import cn.tedu.dfxd.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author DBX
 * @effect
 * @date 2021/10/21/22:03
 */
@RestController
public class UserController {

    @Autowired(required = false)
    UserMapper mapper;




    @RequestMapping("/login")
    public int login(User user, String rem, HttpSession session , HttpServletResponse response) {
        User hr1 = mapper.check(user.getUsername());
        String userPassword = user.getPassword();
        String userPassword1 = DigestUtils.md5DigestAsHex(userPassword.getBytes());
        System.out.println("user = " + user + ", rem = " + rem + ", session = " + session + ", response = " + response);
        if (hr1 != null) {
            if (hr1.getPassword().equals(userPassword1)) {
//                判断是否需要记住密码 Cookie
                if (rem!=null){//如果选中这返回on 没有选中就为null
                    Cookie c1 = new Cookie("username",hr1.getUsername());
                    c1.setMaxAge(60*60*24*30);
                    Cookie c2 = new Cookie("password",userPassword);
                    c2.setMaxAge(60*60*24*3);
                    Cookie c3 = new Cookie("email",hr1.getEmail());
                    c2.setMaxAge(60*60*24*3);
//                    把Cookie下发给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);
                    response.addCookie(c3);
                }
                session.setAttribute("user", hr1);
                return hr1.getStamp();//登录成功 返回用户类型
            } else {
                return 3;//密码错误
            }
        }
        return 2;//用户名不存在
    }
    @RequestMapping("checkLogin")
    public User checkLogin(HttpSession session){
//        把登录成功的session用户传递出去
        return  (User) session.getAttribute("user");
    }

}
